app.factory("connect", ["$http", "$window", "$q", "$location", "$exception", "$indexeddb", "$token", "$canceler", function ($http, $window, $q, $location, $exception, $indexeddb, $token, $canceler) {
    function ConnectService() {
    };

    ConnectService.prototype = {
        connect: function (model) {
            return $http.post("connect", model, { timeout: $canceler.create().promise }).success(function (res) {
                return $token.set(res.token).then(function () {
                    $location.path(res.route);
                });
            }).catch(function (error) {
                return $exception.show(error);
            });
        },
        disconnect: function () {
            return $token.reset().then(function () {
                return $indexeddb.clearAll();
            }).finally(function(){
                $window.location = "/";
            });
        },
        gotoApp: function () {
            return $token.get().then(function (token) {
                return $http.post("connectfrom", {}, { params: { token: token }, timeout: $canceler.create().promise }).success(function (res) {
                    return $token.set(res.token).then(function () {
                        $window.location = "/#" + res.route;
                    });
                });
            }).catch(function (error) {
                $notify.show("Impossible de basculer sur le site publique.");
            });
        },
    };
    return new ConnectService();
} ]);
